from database.database import Database
from model.token import Token
from typing import List


class TokenTable(Database):
    def __init__(self):
        self.table_name = "token"

    def insert(self, token: Token) -> bool:
        record = self.find_user(token)
        if record:
            sql = self.get_update_sql_from_obj(record["id"], token, self.table_name)
        else:
            sql = self.get_insert_sql_from_obj(token, self.table_name)
        self.execute(sql)
        return int(self.cursor.lastrowid)

    def get_latest(
        self, type: int, second: int, max_used: int, limit: int
    ) -> List[Token]:
        sql = f"select * from {self.table_name} where `type` = {type}"
        if second > 0:
            sql += f" and `gmt_modified` > DATE_SUB(NOW(), INTERVAL {second} SECOND)"
        if max_used > 0:
            sql += f" and `used` < {max_used}"
        sql += " ORDER BY `gmt_modified`"
        if limit > 0:
            sql += f" LIMIT {limit}"
        self.execute(sql)
        tokens = [Token().load(record) for record in self.cursor.fetchall()]
        return tokens

    def used(self, token: Token):
        sql = f"update {self.table_name} set `used` = {token.used + 1} where `type` = {token.type} and `userid` = '{token.userid}'"
        self.execute(sql)

    def find_user(self, token: Token) -> Token:
        sql = f"select * from {self.table_name} where `type` = {token.type} and `userid` = '{token.userid}'"
        self.execute(sql)
        record = self.cursor.fetchone()
        return record
